package com.jcl.cloud.services.crawler.email.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.*;

public class ZlzpUtil {
    private static Logger logger = LoggerFactory.getLogger(ZlzpUtil.class);

    private static ScriptEngine engine ;
    static{

        try {
            ScriptEngineManager maneger = new ScriptEngineManager();
            engine = maneger.getEngineByName("JavaScript");

            // 读js文件
            String jsFile = "/app/jcl-crawler/js/map.js";

            FileInputStream fileInputStream = new FileInputStream(new File(jsFile));
            Reader scriptReader = new InputStreamReader(fileInputStream, "utf-8");

            engine.eval(scriptReader);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            e.printStackTrace();
        }

    }



    public static String doCode2Name(String code,String type){

        String result = "未知";
        try {
            code = code.replaceAll(" ","");
            type = type.replaceAll(" ","");
            if (engine instanceof Invocable) {
                Invocable invocable = (Invocable) engine;
                result = (String) invocable.invokeFunction("DoCode2Name",new Object []{code,type});
            }

            logger.info("result = " + result);
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}
